package com.own.component.common.login.util;

import com.own.component.common.exception.BusinessException;
import com.own.component.common.login.user.BaseLoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * UserUtil
 *
 * @author chenxueli
 * @date 2021/5/27 9:35
 */
@Slf4j
@Component
public class UserUtil {

    @Resource
    private HttpServletRequest request;

    /**
     * 根据token获取用户信息
     *
     * @param token    token
     * @param function 获取用户信息的方法
     * @return 用户信息
     */
    public BaseLoginUser getLoginUser(String token, GetLoginUserFunction function) {
        if (token == null) {
            throw new BusinessException("token信息异常");
        }
        return function.get(token);
    }

    /**
     * 从请求中获取token
     *
     * @param key 键
     * @return token
     */
    public String getAuthToken(String space, String key) {
        return switch (space) {
            case Space.COOKIE -> getAuthTokenInCookie(key);
            case Space.HEADER -> getAuthTokenInHeader(key);
            case Space.PARAMETER -> getAuthTokenInParameter(key);
            default -> throw new BusinessException("token获取位置异常");
        };
    }

    /**
     * 从请求的cookie列表中获取token
     *
     * @param key 键
     * @return token
     */
    private String getAuthTokenInCookie(String key) {
        if (RequestContextHolder.getRequestAttributes() == null || request == null) {
            return null;
        }
        var cookies = request.getCookies();
        for (var cookie : cookies) {
            if (key.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }

    /**
     * 从请求的header列表中获取token
     *
     * @param key 键
     * @return token
     */
    private String getAuthTokenInHeader(String key) {
        if (RequestContextHolder.getRequestAttributes() != null && request != null) {
            return request.getHeader(key);
        }
        return null;
    }

    /**
     * 从请求的参数列表中获取token
     *
     * @param key 键
     * @return token
     */
    private String getAuthTokenInParameter(String key) {
        if (RequestContextHolder.getRequestAttributes() != null && request != null) {
            return request.getParameter(key);
        }
        return null;
    }

    public interface GetLoginUserFunction {
        /**
         * 获取token的方法
         *
         * @param token token
         * @return 用户信息
         */
        BaseLoginUser get(String token);
    }

    public interface Space {
        String COOKIE = "cookie";
        String HEADER = "header";
        String PARAMETER = "parameter";
    }

}
